package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.common.R;
import com.example.demo.entity.user.LoginDto;
import com.example.demo.entity.user.LoginVo;
import com.example.demo.entity.user.RegistDto;
import com.example.demo.entity.user.User;
import com.example.demo.exception.BusinessException;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import com.example.demo.service.cache.CacheTokenService;
import com.example.demo.utils.IdUtils;
import com.example.demo.utils.PasswordUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private CacheTokenService cacheTokenService;

    @Override
    public R<Boolean> regist(RegistDto dto) throws Exception {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, dto.getUsername());
        User user = baseMapper.selectOne(wrapper);
        if (user != null) {
            throw new BusinessException("用户名已被使用。");
        }
        String userId = IdUtils.genId(5, false);
        User user1 = new User();
        user1.setId(userId);
        user1.setUsername(dto.getUsername());
        user1.setPassword(PasswordUtils.encrypt(dto.getPassword()));
        user1.setCreateBy(userId);
        user1.setUpdateBy(userId);
        baseMapper.insert(user1);
        return R.ok(true);
    }

    @Override
    public R<LoginVo> login(LoginDto dto) throws Exception {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, dto.getUsername());
        User user = baseMapper.selectOne(wrapper);
        if (user == null) {
            throw new BusinessException("用户不存在。");
        }
        boolean b1 = PasswordUtils.verify(user.getPassword(), dto.getPassword());
        if (!b1) {
            throw new BusinessException("密码错误");
        }
        user.setPassword("");
        String token = cacheTokenService.genToken(user.getId(), user.getUsername(), "???", "???", "???", "???");
        return R.ok(new LoginVo(token, user, "???"));
    }
}
